package com.coco.controller;

import com.coco.mapper.LeaveTypeMapper;
import com.coco.pojo.LeaveType;
import com.coco.utils.ApiResponse;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 请假类型管理控制器
 */
@RestController
@RequestMapping("/api/leaveTypes")
public class LeaveTypeController {

    @Autowired
    private LeaveTypeMapper leaveTypeMapper;

    /**
     * 保存或更新请假类型信息
     * @param leaveType 请假类型对象
     * @return API响应
     */
    @PostMapping("/saveOrUpdate")
    public ApiResponse<Void> saveOrUpdate(@RequestBody LeaveType leaveType) {
        if (leaveType.getId() == null) {
            leaveTypeMapper.insert(leaveType);
        } else {
            leaveTypeMapper.updateById(leaveType);
        }
        return ApiResponse.success("操作成功", null);
    }

    /**
     * 删除指定ID的请假类型
     * @param id 请假类型ID
     * @return API响应
     */
    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Integer id) {
        leaveTypeMapper.deleteById(id);
        return ApiResponse.success("删除成功", null);
    }

    /**
     * 批量删除请假类型
     * @param ids 请假类型ID列表
     * @return API响应
     */
    @DeleteMapping("/batch")
    public ApiResponse<Void> deleteBatch(@RequestBody List<Integer> ids) {
        for (Integer id : ids) {
            leaveTypeMapper.deleteById(id);
        }
        return ApiResponse.success("批量删除成功", null);
    }

    /**
     * 查询所有请假类型信息
     * @return API响应
     */
    @GetMapping
    public ApiResponse<List<LeaveType>> findAll() {
        List<LeaveType> leaveTypes = leaveTypeMapper.selectAll();
        return ApiResponse.success(leaveTypes);
    }

    /**
     * 查询指定ID的请假类型信息
     * @param id 请假类型ID
     * @return API响应
     */
    @GetMapping("/{id}")
    public ApiResponse<LeaveType> findOne(@PathVariable Integer id) {
        LeaveType leaveType = leaveTypeMapper.selectById(id);
        return ApiResponse.success(leaveType);
    }

    /**
     * 分页查询请假类型信息
     * @param pageNum 页码
     * @param pageSize 每页大小
     * @param leaveType 查询条件
     * @return API响应
     */
    @PostMapping("/page")
    public ApiResponse<PageInfo<LeaveType>> findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                                                     @RequestParam(defaultValue = "10") Integer pageSize,
                                                     @RequestBody(required = false) LeaveType leaveType) {
        PageHelper.startPage(pageNum, pageSize);
        List<LeaveType> leaveTypes = leaveTypeMapper.selectByEntity(leaveType);
        PageInfo<LeaveType> pageInfo = new PageInfo<>(leaveTypes);
        return ApiResponse.success(pageInfo);
    }
}